package com.csx.micrometer.invoke.config;

import com.csx.micrometer.invoke.core.outbound.resttemplate.MicrometerRestTemplateBeanPostProcessor;
import com.csx.micrometer.invoke.core.outbound.resttemplate.MicrometerRestTemplateOutboundInterceptor;
import com.csx.micrometer.invoke.custom.TagsCustom;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author cuisongxu
 * @date 2022/12/3 22:51
 */
@ConditionalOnClass(RestTemplate.class)
@Configuration
public class RestTemplateOutboundMicrometerConfiguration {

    @ConditionalOnMissingBean
    @Bean("micrometerRestTemplateOutboundInterceptor")
    public ClientHttpRequestInterceptor micrometerRestTemplateOutboundInterceptor(List<TagsCustom> tagsCustoms) {
        return new MicrometerRestTemplateOutboundInterceptor(tagsCustoms);
    }

    @ConditionalOnMissingBean
    @Bean
    public BeanPostProcessor micrometerRestTemplateBeanPostProcessor() {
        return new MicrometerRestTemplateBeanPostProcessor();
    }

    /**
     * 这是第二种方式在 RestTemplate类型的Bean 中注入自定义的interceptor
     * @param restTemplates RestTemplate类型Bean的列表
     * @param micrometerRestTemplateOutboundInterceptor 要注入的拦截器
     * @return
     */
//    @Bean
//    public SmartInitializingSingleton injectMicrometerRestTemplateOutboundInterceptor(List<RestTemplate> restTemplates,
//                                                                                      ClientHttpRequestInterceptor micrometerRestTemplateOutboundInterceptor) {
//        return () -> {
//            for (RestTemplate restTemplate : restTemplates) {
//                restTemplate.getInterceptors().add(0, micrometerRestTemplateOutboundInterceptor);
//            }
//        };
//    }
}
